package provider;

import enumeration.RpcError;
import exception.RpcException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;

public class ServiceProviderImpl implements ServiceProvider {
    private static final Logger logger = LoggerFactory.getLogger(ServiceProviderImpl.class);

    private static Map<String, Object> serviceMap = new ConcurrentHashMap<>();
    private static Set<String> registeredService = ConcurrentHashMap.newKeySet();
    @Override
    public void addService(String canonicalName, Object object) {
        if (registeredService.contains(canonicalName)) {
            return;
        }
        registeredService.add(canonicalName);
        serviceMap.put(canonicalName, object);
        logger.info("向接口: {} 注册服务: {}", object.getClass().getInterfaces(), canonicalName);
    }

    //添加接口及其实现类对象
    @Override
    public <T> void addService(String service, Class<T> clazz) {
        T t = null;
        try {
            t = clazz.newInstance();
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
        serviceMap.put(service, t);
    }

    @Override
    public Object getService(String serviceName) {
        Object service = serviceMap.get(serviceName);
        if(service == null){
            logger.error("接口没有实现类");
            throw new RpcException(RpcError.SERVICE_NO_FOUND);
        }
        return service;
    }
}
